﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kocic.RepositoryManagement;
using Kocic.RepositoryManagement.EntityFramework4;
using System.Linq.Expressions;
using Sample.EF4.Model;

namespace Sample.Run.EntityFramework4
{
    /// <summary>
    /// Concrete implementation of the EntityDataManager. Manages the Person entity object.
    /// </summary>
    public sealed class PersonRepositoryManager : EntityRepositoryManager<Person, SampleDataModelEntities>
    {
        /* Constructor Note:
         * By default, if using the EntityContextManager for object context handling, then no constructor definitions are needed. However, if the context object is instantiated without using
         * the EntityContextManager class, then the below two constructors would have to be defined */

        public PersonRepositoryManager()
        {

        }

        public PersonRepositoryManager(SampleDataModelEntities context) : base(context)
        {

        }

        public override Person RetrieveSingle(object searchValue)
        {
            if (searchValue == null)
            {
                throw new ArgumentNullException("searchValue", "searchValue cannot be null");
            }

            if (searchValue is Int32)
            {
                Int32 searchId = Convert.ToInt32(searchValue);

                return this.DataSource.People.Where(c => c.id.Equals(searchId)).SingleOrDefault();
            }
            else
            {
                throw new ArgumentException("searchValue must be of type int");
            }
        }

        public override IEnumerable<Person> RetrieveMultiple()
        {
            return this.DataSource.People.Select(p => p);
        }

        public override IEnumerable<Person> RetrieveMultiple(object searchValue)
        {
            throw new NotImplementedException();
        }


        public Person RetrieveSingle(String firstName, String LastName)
        {
            return this.DataSource.People.Where(p => p.FirstName == firstName && p.LastName == LastName).SingleOrDefault();
        }

        /// <summary>
        /// Performs pre-delete operations before an actual deletion is made. Checks to see if the state of the entity object is detached
        /// and if so fetches it from the database and returns it.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected override Person PreDelete(Person dataObject)
        {
            if(this.IsDataObjectInRemovedState(dataObject).Value)
            {
                Person original = this.RetrieveSingle(dataObject.id);

                return original;
            }

            return null;
        }
    }
}